package com.example;

import com.alibaba.fastjson.JSONObject;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

public class ExampleMain {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
        persistEntity(emf);
        /*loadEntities(emf);*/
        queryStudents(emf);
        emf.close();
    }

    private static void persistEntity(EntityManagerFactory emf){
        EntityManager em = emf.createEntityManager();
        Student student = new Student();
        student.setStudentName("Ravan");
        Book book1 = new Book("Ramayan","Valmiki");
        Book book2 = new Book("Mahabharat","Vyas");
        Book book3 = new Book("Nimla","Premchand");
        SortedSet<Book> books = new TreeSet<>();
        books.add(book1);
        books.add(book2);
        books.add(book3);
        student.setBooks(books);

        em.getTransaction().begin();
        em.persist(book1);
        em.persist(book2);
        em.persist(book3);
        em.persist(student);
        em.getTransaction().commit();
        em.close();
    }

    private static void queryStudents(EntityManagerFactory emf){
        EntityManager em = emf.createEntityManager();
        Query query = em.createQuery("select s from Student s");
        List<Student> students = query.getResultList();
        for (Student student : students) {
            for (Book book : student.getBooks()) {
                System.err.println(JSONObject.toJSONString(book,false));
            }
        }
        em.close();
    }

    private static void loadEntities(EntityManagerFactory emf){
        EntityManager em = emf.createEntityManager();
        Student student = em.find(Student.class,1);
        SortedSet<Book> books = student.getBooks();
        for (Book book : books) {
            System.err.println(JSONObject.toJSONString(book,false));
        }
        em.close();
    }
}
